package arithmetic.socket.netty.websocket;

import java.util.Scanner;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @author jiangfeng
 * Created on 2020-03-04
 */
public class WebSocketServer {
    public static void main(String[] args) throws InterruptedException {

        EventLoopGroup worker = new NioEventLoopGroup();
        EventLoopGroup boss = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boss, worker).channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.DEBUG))
                    .childHandler(new WebSocketServerInitialer());
            ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
            // channelFuture.channel().closeFuture().sync();

            Channel channel = channelFuture.channel();
            Scanner scanner= new Scanner(System.in);
            while (scanner.hasNextLine()){
                String msg = scanner.nextLine();
                channel.writeAndFlush(new TextWebSocketFrame(msg));
                System.out.println("发送消息:"+msg);
            }
        } finally {
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }
    }
}
